﻿using ED.IService;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System.Text;

namespace ED.Service
{
    public class RabbitMQService : IRabbitMQService
    {
        private readonly ILogger<RabbitMQService> _logger;
        private readonly IConnection _connection;

        //public RabbitMQService(IConnectionFactory connectionFactory, ILogger<RabbitMQService> logger)
        //{
        //    _connection = connectionFactory.CreateConnection();
        //    _logger = logger;
        //}

        public void SendMessage(string queueName, string message)
        {
            try
            {
                using var channel = _connection.CreateModel();
                /*
                 // 声明一个队列
channel.QueueDeclare(
    queue: queueName,   // 队列名称
    durable: false,     // 是否持久化，true持久化，队列会保存磁盘，服务器重启时可以保证不丢失相关信息
    exclusive: false,   // 是否排他，如果一个队列声明为排他队列，该队列仅对时候次声明它的连接可见，并在连接断开时自动删除
    autoDelete: false,  // 是否自动删除，自动删除的前提是：至少有一个消费者连接到这个队列，之后所有与这个队列连接的消费者都断开时，才会自动删除
    arguments: null     // 设置队列的其他参数
);
                 */
                channel.QueueDeclare(queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "", routingKey: queueName, basicProperties: null, body: body);

                _logger.LogInformation($" [x] Sent {queueName}: {message}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error occured while sending message: {message}");
            }
        }
    }
}